package com.jshoperxms.controller.api.pay;

import com.jshoperxms.Response;
import com.jshoperxms.components.wechat.WxConfig;
import com.jshoperxms.components.wechat.pay.WXParam;
import com.jshoperxms.components.wechat.pay.WXPay;
import com.jshoperxms.components.wechat.pay.WXPayConfigImpl;
import com.jshoperxms.components.wechat.pay.WXPayUtil;
import com.jshoperxms.controller.api.langdu.pojo.OrderPayParams;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.OrderEnums;
import com.jshoperxms.controller.utils.enums.YdEnums;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.MemberT;
import com.jshoperxms.entity.OrderLdgiftT;
import com.jshoperxms.entity.YdArticleRecordRdT;
import com.jshoperxms.service.MemberTService;
import com.jshoperxms.service.OrderLdgiftTService;
import com.jshoperxms.service.YdArticleRecordRdTService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sdywcd on 2019/12/12.
 * Des:朗读礼物支付逻辑
 */
@RestController
@RequestMapping("/api/pay/orderldgift")
public class OrderLdGiftCtr {
    private static final Logger logger = LoggerFactory.getLogger(OrderLdGiftCtr.class);

    @Resource
    private OrderLdgiftTService orderLdgiftTService;

    @Resource
    private YdArticleRecordRdTService ydArticleRecordRdTService;

    @Resource
    private MemberTService memberTService;


    private WXPayConfigImpl payConfig;

    public OrderLdGiftCtr() throws Exception {
        payConfig = WXPayConfigImpl.getInstance();
    }


    /**
     * 创建朗读打赏礼物订单并生成预支付订单
     *
     * @return
     */
    @Transactional(rollbackOn=Exception.class)
    @RequestMapping(value = "/createLdGiftOrderThenPay", method = RequestMethod.POST)
    public ResponseEntity createLdGiftOrderThenPay(@RequestBody OrderPayParams rq) throws Exception {
        Map<String, Object> responsedata = new HashMap<>();
        if (StringUtils.isNotBlank(rq.getWxopenid()) && StringUtils.isNotBlank(rq.getYdarticleid())) {
            //检查朗读文章是否存在
            YdArticleRecordRdT ydArticleRecordRdT = this.ydArticleRecordRdTService.findByPK(YdArticleRecordRdT.class, rq.getYdarticleid());
            Criterion criterion = Restrictions.eq("wxopenid", rq.getWxopenid());
            MemberT memberT = this.memberTService.findOneByCriteria(MemberT.class, criterion);
            if (ydArticleRecordRdT != null && memberT != null) {
                //生成本地朗读礼物打赏订单
                OrderLdgiftT orderLdgiftT = new OrderLdgiftT();
                orderLdgiftT.setOrderid(DateTools.getSystemTimeBi().toString());
                orderLdgiftT.setWxopenid(rq.getWxopenid());
                orderLdgiftT.setTowxopenid(ydArticleRecordRdT.getWxopenid());
                orderLdgiftT.setTomemberid(StringUtils.EMPTY);
                orderLdgiftT.setMemberid(memberT.getId());
                orderLdgiftT.setMembername(memberT.getNick());
                orderLdgiftT.setOrderstatus(OrderEnums.OrderStatus.ORDERSTATE_CONFIRMED_ONE_NUM.getState());
                orderLdgiftT.setAmount(BigDecimal.valueOf(Double.parseDouble(rq.getAmount())));
                orderLdgiftT.setGleafs(50);
                orderLdgiftT.setPurchasetime(DateTools.getSystemTimeBi());
                orderLdgiftT.setNeedinvoice(OrderEnums.IsneedInvoice.NO.getState());
                orderLdgiftT.setPaytime(BigInteger.valueOf(0L));
                orderLdgiftT.setOrdertag(OrderEnums.OrderCreateTag.ORDERTAG_NORMAL_ONE_NUM.getState());
                orderLdgiftT.setTobuyernote(StringUtils.EMPTY);
                orderLdgiftT.setShouldpay(BigDecimal.valueOf(Double.parseDouble(rq.getAmount())));
                orderLdgiftT.setNeedquantity(1);
                orderLdgiftT.setPaystatus(OrderEnums.OrderPayState.ORDERPAYSTATE_UNPAY_ZERO_NUM.getState());
                orderLdgiftT.setCreatetime(DateTools.getSystemTimeBi());
                orderLdgiftT.setTradenumber(StringUtils.EMPTY);
                orderLdgiftT.setBasicuserid(StringUtils.EMPTY);
                orderLdgiftT.setBasicusername(StringUtils.EMPTY);
                orderLdgiftT.setErrorordertag(StringUtils.EMPTY);
                orderLdgiftT.setVersiont(1);
                orderLdgiftT.setOrdername("朗读鼓励打赏" + memberT.getNick() + DateTools.getSystemTimeBi().toString());
                orderLdgiftT.setUpdatetime(DateTools.getSystemTimeBi());
                orderLdgiftT.setStatus(BaseEnums.DataUsingState.USING.getState());
                this.orderLdgiftTService.save(orderLdgiftT);

                //微信统一下单
                double totalfee = Double.valueOf(rq.getAmount());
                String nonce_str = WXPayUtil.generateUUID();
                Map<String, String> orderData = new HashMap<>();
                orderData.put("appid", WxConfig.appid);
                orderData.put("mch_id", WxConfig.mchid);
                orderData.put("nonce_str", nonce_str);
                orderData.put("body", "朗读能手鼓励打赏");
                orderData.put("out_trade_no", orderLdgiftT.getOrderid());
                orderData.put("total_fee", String.valueOf((int) totalfee));
                orderData.put("spbill_create_ip", payConfig.getHostIP());
                orderData.put("notify_url", payConfig.getNotifyUrl());
                orderData.put("trade_type", payConfig.getTradeType());
                orderData.put("sign_type", payConfig.getSignType());
                orderData.put("openid", memberT.getWxopenid());
                orderData.put("attach", YdEnums.PAYBUSTYPE.PAYFORTEAMARTICLE.getState());
                String sign = WXPayUtil.generateSignature(orderData, payConfig.getKey());
                orderData.put("sign", sign);
                WXPay wxPay=new WXPay(payConfig,payConfig.getNotifyUrl());
                Map<String, String> orderResult =wxPay.unifiedOrder(orderData);
                if (orderResult.get("return_code").equals("SUCCESS") && orderResult.get("return_msg").equals("OK") && orderResult.get("result_code").equals("SUCCESS")) {
                    String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
                    Map<String, String> payData = new HashMap<>();
                    payData.put("appId", payConfig.getAppID());
                    payData.put("timeStamp", timeStamp);
                    payData.put("nonceStr", nonce_str);
                    payData.put("package", "prepay_id=" + orderResult.get("prepay_id").toString());
                    payData.put("signType", payConfig.getSignType());
                    String paySign = WXPayUtil.generateSignature(payData, payConfig.getKey());
                    // 3.封装支付信息
                    WXParam wxParam = new WXParam();
                    wxParam.setAppId(payConfig.getAppID());
                    wxParam.setTimestamp(timeStamp);
                    wxParam.setNonceStr(nonce_str);
                    wxParam.setPackages("prepay_id=" + orderResult.get("prepay_id"));
                    wxParam.setSignType(payConfig.getSignType());
                    wxParam.setSign(paySign);
                    responsedata.put(TagWords.SUCCESS, true);
                    responsedata.put("wxparams", wxParam);
                } else {
                    responsedata.put(TagWords.SUCCESS,false);
                    responsedata.put(TagWords.MSG, WarnWrods.WECHAT_PAY_ERROR);
                }
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,WarnWrods.EMPTY_RECORD);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }
}
